﻿using Coomtools.commclass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Coomtools.weightclasses
{
    //*****************************************
    //*****************精函，有声称**********
    //*****************************************
    public class JHScale : Myweightbase, IweightInteface
    {
        //*********************************dll导入*****************************
        const string LibraryName = "ExtrDlls/JHScale.dll";

        //const string LibraryName = "JHScale.dll";
        [DllImport(LibraryName)]
        private static extern int JHScale_TxDevice_Sim();
        [DllImport(LibraryName)]
        private static extern int JHScale_TxDevice(byte[] pIP, byte[] pFileName);


        //******************精函内部数据结构声明*********************************

        //public Dictionary<string, string> D_WeightUnitflag = new Dictionary<string, string>();
        /// <summary>
        /// 接受界面传来的plu集合
        /// </summary>
        private BindingList<Uipluitem> InuipluList = new BindingList<Uipluitem>();
        const string WritePLUFileName = "Plu.txt";
        int AllCount=0;
        //********************************************************

        /// <summary>
        /// 无参构造函数
        /// </summary>
        public JHScale()
        {
            InitThisClass();
        }

        public JHScale(BindingList<Uipluitem> InUIpluList)
        {
            InuipluList = InUIpluList;

            InitThisClass();

        }


        /// <summary>
        /// 初始化本类 的方法 对各种解析定义函数
        /// </summary>
        public void InitThisClass()
        {
            //  *********能解析的单位定义*********

            D_WeightUnitflag.Add("1", "公斤");
            D_WeightUnitflag.Add("2", "pcs(kg)");
            D_WeightUnitflag.Add("3", "公斤");
            D_WeightUnitflag.Add("4", "克");
            D_WeightUnitflag.Add("5", "吨");
            D_WeightUnitflag.Add("6", "磅");
            D_WeightUnitflag.Add("7", "500g");
            D_WeightUnitflag.Add("8", "100g");
            //  *********能解析的条码类型定义*********

        }
      /// <summary>
      /// 检查是否是文本文件
      /// </summary>
      /// <param name="readfilepath"></param>
      /// <returns></returns>
        public bool CheckIsNeedFile(string readfilepath)
        {
            return FileoperHelper.CheckIsTextFile(readfilepath);
        }

        /// <summary>
        ///在字典里通过value找key
        /// </summary>
        /// <param name="D_WeightUnitflag">字典</param>
        /// <param name="value">value</param>
        /// <returns>key值 或 null</returns>
        string GetDictionaryKey(Dictionary<string, string> D_WeightUnitflag, string value)
        {

            foreach (var key in D_WeightUnitflag.Keys)
            {
                if (D_WeightUnitflag[key].Equals(value))
                {
                    return key;
                }
            }
            return null;


        }

        /// <summary>
        /// 查找精函数字单位标识对应的（汉字）单位名称
        /// </summary>
        /// <param name="weightunitflag"></param>
        /// <returns></returns>
        public string findMyWeightUnitFlag(string weightunitflag)
         {
        

            foreach (var item in D_WeightUnitflag.Keys)
            {
                if (item == weightunitflag)
                    return D_WeightUnitflag[item];

            }

            return weightunitflag;

        
        }



        public bool Link_EWeightOK(string IPAdress, string port)
        {
            if (File.Exists(LibraryName))
            {
          return true;
            }
            else
            {
                return false;
            }  
        }

        public dynamic ReadPLuResourseFile(string readfilepath)
        {
            //生成界面控件需要的PLU list集合
            BindingList<Uipluitem> RPLUList = new BindingList<Uipluitem>();
           
           Encoding encoding = Encoding.Default;
           StreamReader streamreader= new StreamReader(readfilepath, encoding);;
            try
            {
                int count = 1; 
                while (streamreader.Peek() != -1)
               {
                string sreadline = streamreader.ReadLine();
                string[] s = sreadline.Split('\t');
                Uipluitem rp = new Uipluitem();
                rp.serialnumber = count.ToString();
              
                rp.pluname = s[4];
                rp.PLUcode = s[1];
                rp.lfcode = s[2];

                rp.price = (Convert.ToDouble(s[5])).ToString("0.00");
                 rp.unit=s[6];
                  rp.unitcode = rp.unit;
                    //****************解析单位 ************* 

                    rp.unit = findMyWeightUnitFlag(rp.unit);

                    //*****************将热键字符去掉前导0 并保留3位热键***********
                    Regex reg = new Regex(@"^0+");
                    rp.HotKey = rp.PLUcode;
                    string hotkey1 = rp.HotKey;
                    if (hotkey1.Length >= 3)
                    {
                        hotkey1 = rp.HotKey.Substring(rp.HotKey.Length - 3, 3);
                        rp.HotKey = reg.Replace(hotkey1, "");
                    }
                    else
                    {
                        rp.HotKey = reg.Replace(hotkey1, "");
                    }

                    //源文件包含热键定义可以读取出来暂时不用hotkey
                    //rp.HotKey = s[9];
                  
                    RPLUList.Add(rp);
                count++;

              }
           
            streamreader.Close();
            }
            catch (Exception ex)
            {
                streamreader.Close();
                throw ex;
            }
           
            
            return RPLUList;

        }
        public void WriteUiPluListToFile(BindingList<Uipluitem> InuipluList)
        {
            //将PLU信息写入 PLU.txt文件中
            string WriteplufilePath = WritePLUFileName;

            StreamWriter sw = new StreamWriter(WriteplufilePath, false, Encoding.Default);
            try
            {
              
                foreach (var InPluitem in InuipluList)
                {
                    //？？？？？？后期 改？？？？？？？？？ 当条码格式为0表示为定义 将他强制转换为2目前
                    if (InPluitem.barcodeclassCode == "0")
                    {
                        InPluitem.barcodeclassCode = "2";

                    }

                    //将汉字的单位名 重新解析为 对应的数字
                    string getweightunit = GetDictionaryKey(D_WeightUnitflag, InPluitem.unit);

                    if (getweightunit != null)

                        InPluitem.unitcode = getweightunit;

                    else
                        //没找到单位对照表的按1 的方式公斤传
                        InPluitem.unitcode = "1";

                    string w = "PLU"+ "\t" + InPluitem.PLUcode+ "\t" + InPluitem.lfcode + "\t"  + "\t" + InPluitem.pluname
                            + "\t" + InPluitem.price + "\t" + InPluitem.unitcode + "\t" +"1"+ "\t" + "0";
                    sw.WriteLine(w);
                }

                sw.Close();
            }
            catch (Exception ex)
            {
                sw.Close();
                throw ex;
            }



            ////将热键写入HotKey.key文件中
            //string WriteHotkeyPath = WritePLUHotKeyFileName;
            //var swhotkey = new StreamWriter(WriteHotkeyPath, false, Encoding.Default);
            //try
            //{

            //    string Aclas32HotKeyFileHeard = "ButtonIndex\tButtonValue";
            //    swhotkey.WriteLine(Aclas32HotKeyFileHeard);
            //    foreach (var uiplu in InuipluList)
            //    {
            //        int hotkey = 1;
            //        try
            //        {
            //            hotkey = Convert.ToInt32(uiplu.HotKey);
            //        }
            //        catch (Exception ex)
            //        {
            //            hotkey = 0;

            //            throw ex;
            //        }
            //        if (hotkey > 0 && hotkey < 225)
            //        {
            //            string w = uiplu.HotKey + "\t" + uiplu.PLUcode;
            //            swhotkey.WriteLine(w);
            //        }
            //    }
            //    swhotkey.Close();

            //}
            //catch (Exception ex)
            //{
            //    swhotkey.Close();
            //    throw ex;
            //}



        }
        public int StartTranfPLU(string IPAdress, string port)
        {
              WriteUiPluListToFile(InuipluList);

            if (File.Exists (WritePLUFileName))
            {
                int rv = JHScale_TxDevice(Encoding.ASCII.GetBytes(IPAdress), Encoding.ASCII.GetBytes(WritePLUFileName));
                if (rv==0)
                {
                    AllCount = InuipluList.Count;
                    return AllCount;
                }
                else
                {
                    return -1;
                }
            }
            else
            return -1;

            //if (IPinTextButton.Checked)
            //{
            //    //此处写入的文件JHScaleT.txt必须与JHScale.ini中TxFile的描述相同
            //    //The file to be write must be the same as TxFile in JHScale.ini
            //    FileStream fs = new FileStream("JHScaleT.txt", FileMode.Create);
            //    StreamWriter sw = new StreamWriter(fs);
            //    sw.WriteLine("ZTD\t" + IP_TextBox.Text);
            //    sw.Write(contentTextBox.Text);
            //    sw.Flush();
            //    sw.Close();
            //    fs.Close();
            //    int rv = JHScale_TxDevice_Sim();
            //    if (rv == 0)
            //        ;//success
            //    else if (rv == 1)
            //        ;//Connect failed
            //    else if (rv == 2)
            //        ;//File error;
            //}
            //else if (IPinAPIButton.Checked)
            //{
            //    //You can use all name here.
            //    //此处可以是任意的文件名，但如果文件名包含中文，则“Encoding.ASCII.”的部分需要做相应修改，以确保中文以dll能识别的编码方式传递。
            //    string FileName = "NewFile.txt";
            //    FileStream fs = new FileStream(FileName, FileMode.Create);
            //    StreamWriter sw = new StreamWriter(fs);
            //    sw.Write(contentTextBox.Text);
            //    sw.Flush();
            //    sw.Close();
            //    fs.Close();
            //    int rv = JHScale_TxDevice(Encoding.ASCII.GetBytes(IP_TextBox.Text), Encoding.ASCII.GetBytes(FileName));
            //    if (rv == 0)
            //        ;//success
            //    else if (rv == 1)
            //        ;//Connect failed
            //    else if (rv == 2)
            //        ;//File error;
            //}

        }

        public int StartTranHotKey(string IPAdress, string port)
        {
            return 0;
        }

        public bool Close_EWeightConnect(string IPAdress, string port)
        {
            return true;
        }
    }
}
